package com.wgj.android.dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;


import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.jiaai.xui.XUI;
import com.jiaai.xui.utils.XBitmapUtils;
import com.jiaai.xui.utils.XDensityUtils;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.share.ShareUtils;
import com.jiaai.xui.utils.share.entity.Share;
import com.jiaai.xui.view.widget.XToast;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wgj.android.R;
import com.wgj.android.entity.SystemConfg;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;

import java.io.File;
import java.io.FileOutputStream;

import butterknife.BindInt;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CardShareDialog  extends AppCompatDialogFragment implements ShareDiadlog.OnShareListener{
    private JSONObject cards;
    @BindView(R.id.tx_vx)
    TextView vx;
    @BindView(R.id.tx_address)
    TextView address;
    @BindView(R.id.tx_role)
    TextView role;
    @BindView(R.id.tx_iphone)
    TextView iphone;
    @BindView(R.id.tx_unit)
    TextView unit;
    @BindView(R.id.tx_intro)
    TextView intro;
    @BindView(R.id.tx_nickname)
    TextView nickname;
    @BindView(R.id.tx_email)
    TextView email;

    @BindView(R.id.avater)
    ImageView avater;


    @BindView(R.id.tv_cord)
    ImageView tv_cord;
    @BindView(R.id.rootView)
    View rootView;

    @BindView(R.id.shareView)
    View shareView;
    private  ShareDiadlog shareDiadlog;
    private SystemConfg confg;
    private  IWXAPI api;
    public static CardShareDialog getInstael( String cards) {
        CardShareDialog cardShareDialog = new CardShareDialog();
        Bundle bundle = new Bundle();
        bundle.putString("cards", cards);
        cardShareDialog.setArguments(bundle);
        return cardShareDialog;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
        shareDiadlog=new ShareDiadlog().setOnShareListener(this);
         String s=getArguments().getString("cards");
         try{
             cards=JSONObject.parseObject(s);
             confg=CacheUtils.getSystemConfig();
             api = WXAPIFactory.createWXAPI(getContext(), confg.getWXAppId(), true);
             api.registerApp(confg.getWXAppId());
         }catch (Exception e){

         }
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.card_share_dialog,null);
        ButterKnife.bind(this,view);
        initView();
        return view;
    }

    private  void  initView(){
            if(cards!=null){
                vx.setText(cards.containsKey("vx")?cards.getString("vx"):"");
                address.setText(cards.containsKey("address")?cards.getString("address"):"");
                role.setText(cards.containsKey("role")?cards.getString("role"):"");
                iphone.setText(cards.containsKey("iphone")?cards.getString("iphone"):"");
                unit.setText(cards.containsKey("unit")?cards.getString("unit"):"");
                intro.setText(cards.containsKey("intro")?cards.getString("intro"):"");
                nickname.setText(cards.containsKey("nickname")?cards.getString("nickname"):"");
                email.setText(cards.containsKey("email")?cards.getString("email"):"");
                Glide.with(getContext()).load(cards.getString("avatar")).into(avater);
                Glide.with(getContext()).load(WGJAPI.getShareCardUrl(cards.getString("id"))).into(tv_cord);
                GradientDrawable drawable = new GradientDrawable();
                drawable.setCornerRadius(getResources().getDimension(R.dimen.radius));
                drawable.setStroke(1, Color.parseColor(cards.containsKey("model")?cards.getString("model"):"#FF9933"));
                drawable.setColor(Color.TRANSPARENT);
                rootView.setBackground(drawable);
            }
    }
    @Override
    public void onStart() {
        super.onStart();
        getDialog().setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = XDensityUtils.getScreenWidth()-XDensityUtils.dp2px(20f);
        lp.gravity= Gravity.CENTER;
        lp.height =  WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
    }

    @OnClick(R.id.toShareBut)
    public  void  onShare(View view){
//        String path=getSDCardPath()+"/share/card";
//        File file=new File(path);
//        if(!file.exists()){
//            file.mkdirs();
//        }
//        File shareFile=new File(path+"/mId_"+ CacheUtils.getMember().getM_id()+"_card.png");
//        GetandSaveCurrentImage(shareFile);
        shareDiadlog.show(getChildFragmentManager(),"shareDialog");

    }

    private Bitmap loadBitmapFromView() {
        int w = shareView.getWidth();
        int h = shareView.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);

        shareView.layout(0, 0, w, h);
        shareView.draw(c);

        return bmp;
    }
    /**
     * 获取和保存当前屏幕的截图
     */
    private void GetandSaveCurrentImage(File file)
    {
        Bitmap Bmp = loadBitmapFromView();
        //3.保存Bitmap
        try {

            file.createNewFile();
            FileOutputStream fos = null;
            fos = new FileOutputStream(file);
            if (null != fos) {
                Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                getContext().getApplicationContext().sendBroadcast(intent);
                XToast.success("截屏文件已保存至"+file.getPath(),3000);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SDCard的目录路径功能
     * @return
     */
    private String getSDCardPath(){
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if(sdcardExist){
            sdcardDir = Environment.getExternalStorageDirectory();
        }
        return sdcardDir.toString();
    }


    @Override
    public void onShareQQ() {
        XToast.error("暂未开放");
    }

    @Override
    public void onShareWeiXin() {
        if(XEmptyUtils.isSpace(confg.getWXAppId())){
            XToast.error("暂未开放");
        }else {
            Bitmap bitmap=loadBitmapFromView();
            WXImageObject imgWX = new WXImageObject(bitmap);
            WXMediaMessage mediaMessage=new WXMediaMessage();
            mediaMessage.mediaObject=imgWX;
            Bitmap th=Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.3),(int) (bitmap.getHeight()*0.3),true);
            bitmap.recycle();
            mediaMessage.thumbData=XBitmapUtils.getBytesFromBitmap(th);
            th.recycle();
            SendMessageToWX.Req req=new SendMessageToWX.Req();
            req.transaction=buildTransaction("img");
            req.message=mediaMessage;
            req.scene=0;
            api.sendReq(req);
            dismiss();
        }
    }

    @Override
    public void onShareFriends() {
        if(XEmptyUtils.isSpace(confg.getWXAppId())){
            XToast.error("暂未开放");
        }else {
            Bitmap bitmap=loadBitmapFromView();
            WXImageObject imgWX = new WXImageObject(bitmap);
            WXMediaMessage mediaMessage=new WXMediaMessage();
            mediaMessage.mediaObject=imgWX;
            Bitmap th=Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.3),(int) (bitmap.getHeight()*0.3),true);
            bitmap.recycle();
            mediaMessage.thumbData=XBitmapUtils.getBytesFromBitmap(th);
            th.recycle();
            SendMessageToWX.Req req=new SendMessageToWX.Req();
            req.transaction=buildTransaction("webpage");
            req.message=mediaMessage;
            req.scene=1;
            api.sendReq(req);
            dismiss();
        }
    }

    @Override
    public void onShareSpaceBut() {
        XToast.error("暂未开放");
    }

    @Override
    public void onlinkButBut() {
        XToast.error("暂未开放");
    }

    private static String buildTransaction(String type) {
        return type == null?String.valueOf(System.currentTimeMillis()):type + System.currentTimeMillis();
    }

}
